package com.example.demo1.controller;

import com.example.demo1.common.WrapMapper;
import com.example.demo1.common.Wrapper;
import com.example.demo1.entity.Teacher;
import com.example.demo1.service.TeacherService;
import com.example.demo1.util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/teach")
public class TeacherController {
    @Autowired
    TeacherService teacherService;

    // 1、注册
    @PostMapping("/registerTeach")
    public Wrapper registerTeach(HttpServletRequest request, @Validated @RequestBody Teacher teacher) {
        // 获取角色信息
        String role = (String) request.getAttribute("role");

        // 权限验证（假设只有老师可以注册老师）
        if (!"TEACHER".equals(role)) {
            return WrapMapper.error("无权访问");
        }

        return teacherService.registerTeach(teacher);
    }

    // 2、登录 - 修改返回Token
    @PostMapping("/loginTeach")
    public Wrapper loginTeach(@RequestBody Teacher teacher, HttpServletRequest request) {
        Wrapper loginResult = teacherService.loginTeach(teacher.getTc_name(), teacher.getTc_id());

        // 如果登录成功，生成Token
        if (loginResult.getCode() == 200) {
            String token = JWTUtil.generateToken(teacher.getTc_name(), "TEACHER");
            // 将token加入返回结果
            loginResult.setToken(token);
        }

        request.getSession().setAttribute("userInfo", teacher);
        return loginResult;
    }

}
